/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.job.admin.executor;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.lvyh.lightframe.job.admin.util.HttpUtils;
import com.lvyh.lightframe.job.admin.util.NetUtils;
import com.lvyh.lightframe.job.admin.job.HttpJob;
import com.lvyh.lightframe.job.client.InvokeResult;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

/**
 * HTTP service scheduling executor
 */
@Service
public class HttpJobExecutor {
    private Logger logger = LoggerFactory.getLogger(HttpJobExecutor.class);

    public InvokeResult execute(JobExecutionContext context, HttpJob job) {
        JobDataMap dataMap = context.getMergedJobDataMap();

        String httpUrl = (String) dataMap.get("httpUrl");
        String httpMethod = (String) dataMap.get("httpMethod");
        Integer timeout = (Integer) dataMap.get("timeout");
        timeout = (timeout == null || timeout <= 0 || timeout > 120000) ? 120000 : timeout;
        String params = (String) dataMap.get("params");

        Map<String, String> paramMap = null;
        if (StringUtils.isNotBlank(params)) {
            paramMap = JSON.parseObject(params, Map.class);
        }

        Map<String, Object> invokeParams = Maps.newHashMap();
        invokeParams.put("source", NetUtils.getHostAddress());
        invokeParams.put("password", "");
        invokeParams.put("params", paramMap);

        Map<String, String> httpParams = Maps.newHashMap();
        httpParams.put("paramInfo", JSON.toJSONString(invokeParams));
        InvokeResult result = new InvokeResult();
        try {
            if (Objects.equals("GET", httpMethod)) {
                result = HttpUtils.doGet(httpUrl, timeout, httpParams);
            } else if (Objects.equals("POST", httpMethod)) {
                result = HttpUtils.doPost(httpUrl, timeout, httpParams);
            } else {
                throw new RuntimeException("Unsupported http method:" + httpMethod);
            }
            if (result != null && !result.isSuccess()) {
                logger.error("HTTP-RPC-ERR：{}\r\nJobData={}", result.getDescription(), JSON.toJSONString(context.getJobDetail().getJobDataMap()));
            }
            logger.info("[HttpJobExecutor] http service execute success, url:{}", httpUrl);
        } catch (Exception e) {
            logger.error("HTTP-RPC-ERR：{}\r\nJobData={}", e.getMessage(), JSON.toJSONString(context.getJobDetail().getJobDataMap()));
            result.setCode("HTTP-RPC-ERR");
            result.setSuccess(false);
            result.setFailedCount(1);
            result.setDescription(e.getMessage());
        }

        return result;
    }
}
